﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IceDog.Lib.IceDogLog
{
    public static class IceDogLog2
    {
        private static bool _isOpen = true;

        /// <summary>
        /// 日志路径
        /// </summary>
        public static string LogPath
        {
            get
            {
                return AppDomain.CurrentDomain.BaseDirectory + "ErrorLog";
            }
        }
        /// <summary>
        /// 是否打开输出日志
        /// </summary>
        public static bool IsOpen
        {
            get { return _isOpen; }
            set { _isOpen = value; }
        }

        /// <summary>
        /// 格式化错误信息
        /// </summary>
        /// <param name="message">错误信息</param>
        /// <param name="group">日志分组名</param>
        /// <returns></returns>
        private static string FormatMessage(string message, string group = "log")
        {
            var head = "======[" + group + "]======[Time:" + DateTime.Now.ToString("hh:mm:ss") + "]======" + "\r\n>>>\r\n";
            var content = "LOG:" + message + "\r\n>>>\r\n";
            var foot = "======[" + group + "]======[end]======\r\n\r\n";
            return head + content + foot;
        }

        /// <summary>
        /// 写错误日志
        /// </summary>
        /// <param name="message">错误信息</param>
        /// <param name="group">日志分组名</param>
        public static void WriteLog(string message, string group = "")
        {
            if (!IsOpen)
            {
                return;
            }
            if (!Directory.Exists(LogPath))
            {
                Directory.CreateDirectory(LogPath);
            }
            var fileName = DateTime.Now.ToString("yyyy-MM-dd") + ".log";
            if (group.Length != 0)
            {
                fileName = string.Concat(group, "-", fileName);
            }
            fileName = Path.Combine(LogPath, fileName);
            var sw = new StreamWriter(fileName, true);
            sw.Write(FormatMessage(message, group));
            sw.Close();
        }
    }
}
